﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Win32;

namespace SqlScriptVault.Services
{
    public class FileService : IFileService
    {
        public string OpenFileDialog(string extension, string filter)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.DefaultExt = extension;
            openFileDialog.Filter = filter;
            openFileDialog.Multiselect = false;

            bool? result = openFileDialog.ShowDialog();

            if (result.HasValue && result.Value)
            {
                return openFileDialog.FileName;
            }

            return null;
        }

        public string SaveFileDialog(string extension, string filter)
        {
            SaveFileDialog openFileDialog = new SaveFileDialog();
            openFileDialog.DefaultExt = extension;
            openFileDialog.Filter = filter;

            bool? result = openFileDialog.ShowDialog();

            if (result.HasValue && result.Value)
            {
                return openFileDialog.FileName;
            }

            return null;
        }

        public bool Exists(string fileName)
        {
            return File.Exists(fileName);
        }


        public T LoadFile<T>(string fileName)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
            {
                BinaryFormatter binfom = new BinaryFormatter();
                T loadedObject = (T)binfom.Deserialize(fileStream);

                return loadedObject;
            }
        }

        public void SaveFile<T>(string fileName, T objectToSave)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
            {
                BinaryFormatter binfom = new BinaryFormatter();
                binfom.Serialize(fileStream, objectToSave);
            }
        }
    }
}
